<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <!-- slot="before"和#"before"两种写法
        slot="before"这种写法可以在组件和元素中使用
        #"before"只能在组件使用
         -->
        <span slot="before">共166条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportExcel">导出</el-button>
          <el-button
            v-if="checkPerm('addEmployee')"
            size="small"
            type="primary"
            icon="plus"
            @click="ShowDialog = true"
          >新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <!-- 以data传入数组 -->
        <!-- 每列应该显示什么用 prop 属性指定 -->
        <el-table border :data="employeeList">
          <el-table-column label="序号" sortable="" type="index" :index="customIndex" />
          <el-table-column label="头像" width="200">
            <template v-slot="scoped">
              <img
                v-fiximg="require('@/assets/common/head.jpg')"
                :src="scoped.row.staffPhoto"
                alt=""
                class="avatar"
              >
            </template>
          </el-table-column>
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="手机" sortable="" prop="mobile" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formatEmployment" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <template v-slot="scoped">
              <!-- formatDate过滤器，用|术名叫管道 -->
              {{ scoped.row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template v-slot="scoped">
              <!-- active-value，开启开关 -->
              <!-- inactive-value，关闭开关 -->
              <el-switch
                v-model="scoped.row.enableState"
                :active-value="1"
                :inactive-value="2"
                disabled
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{row}">
              <!-- 接收参数，拼接id，在路由配置页面添加：id -->
              <el-button type="text" size="small" @click="$router.push('/employees/detail/'+row.id)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="assignRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="deleteEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :total="total"
            :page-size="pageConfig.size"
            layout="prev, pager, next"
            @current-change="currentChange"
          />
        </el-row>
      </el-card>
      <!-- 新增组件 -->
      <AddDemployee :show-dialog.sync="ShowDialog" />
      <!-- 员工分配角色 -->
      <AssignRole ref="assignRole" :is-show-dialog.sync="isShowRole" />
    </div>
  </div>
</template>

<script>
import { getEmployee, delEmployee } from '@/api/employess'
import EmployeeEnum from '@/api/constant/employees'
import AddDemployee from './components/add-employee'
import AssignRole from './components/assign-role.vue'
import { export_json_to_excel } from '@/vendor/Export2Excel'
import { formatDate } from '@/filters'
export default {
  components: {
    AddDemployee,
    AssignRole
  },
  data() {
    return {
      pageConfig: {
        page: 1,
        size: 5
      },
      employeeList: [],
      total: 0,
      ShowDialog: false,
      isShowRole: false
    }
  },
  created() {
    this.loadPage()
  },
  methods: {
    // checkPerm(pointName) {
    //   // 第二层权限数据在 roles.points 里面
    //   const points = this.$store.state.user.profile.roles.points
    //   return points.includes(pointName)
    // },
    // 分配员工角色
    async assignRole(id) {
      // 调用子组件回显数据函数
      await this.$refs.assignRole.getRoleIds(id)
      this.isShowRole = true
    },
    customIndex(index) {
      // 索引应该等于前面的所有数据数量
      // 继续往下加
      // 前面所有数量=上一页页码*每页长度
      // 比如现在在第三页每页5条, 之前就有 2 * 5 共 10 数据
      // 接下来就是 11 12 13 ...
      return (this.pageConfig.page - 1) * this.pageConfig.size + index + 1
    },
    // 因为后面要多次使用，所以可以先封装起来方便复用
    async loadPage() {
      const { rows, total } = await getEmployee(this.pageConfig)
      this.total = total
      // 这里后端的数据跟我们的预期不一样, 可以造些假数据测试功能
      // 1. 日期希望是完整的日期字符串
      // 2. 账号状态希望有数据
      this.employeeList = rows.map(user => {
        const date = new Date()
        return {
          ...user,
          timeOfEntry: date.toString(),
          enableState: 1
        }
      })
    },
    // 翻页函数，每点击一次翻页会返回一个newPage
    currentChange(newPage) {
      this.pageConfig.page = newPage
      // 每翻一次就调用一下列表接口
      this.loadPage()
    },
    formatEmployment(row, col, cell) {
      // Number转换成字符串
      const res = EmployeeEnum.hireType.find(item => Number(item.id) === Number(cell))
      return res ? res.value : '未知形式'
    },
    // 删除员工
    async deleteEmployee(id) {
      try {
        await this.$confirm('您确定删除该员工吗')
        await delEmployee(id)
        this.loadPage()
        this.$message.success('删除成功')
      } catch (error) {
        console.log(error)
      }
    },
    async exportExcel() {
      // 获取全部员工
      const { rows } = await getEmployee({ page: 1, size: this.total })
      console.log('获取全部员工', rows)

      // 2、演示生成excel的库
      // export_json_to_excel({
      //   header: ['姓名', '年龄', '地址'],
      //   data: [
      //     ['tom', 12, '珠吉路'],
      //     ['小陈', 19, '吉山幼儿园']
      //   ]
      // })
      // 翻译字典
      const dict = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // 用object.keys获取对象key组成表头
      const header = Object.keys(dict)
      console.log('表头', header)

      // 遍历全部员工数组，再另外声明一个空数组存数据，用for in 循环全部员工数组转成英文推入声明的数组
      const data = rows.map(user => {
        const arr = []
        for (const key in dict) {
          // 特殊情况，遇到聘用形式或者时间需要特别处理
          // 聘用形式
          if (dict[key] === 'formOfEmployment') {
            const val = user[dict[key]]
            const res = EmployeeEnum.hireType.find(item => item.id === val)
            arr.push(res ? res.value : '未知')
            // 处理入职和转正日期
          } else if (dict[key] === 'timeOfEntry' || dict[key] === 'correctionTime') {
            const val = user[dict[key]]
            // formatDate引入过滤器，之前已经处理过时间格式
            arr.push(formatDate(val))
          } else {
          // 按照字典的顺序拿到每一个属性推入数组中，dict[key]]英文,就是：后面的值(value值)，在user中取值推到arr数组中去
            arr.push(user[dict[key]])
          }
        }
        return arr
      })
      console.log(data)
      // 调用生成工具下载excel
      export_json_to_excel({
        header,
        data
      })
    }
  }
}
</script>

<style lang='scss' scoped>
.avatar{
  width: 180px;
  height: 100px;
  object-fit: contain;

}
</style>
